package com.example.glide_test.request;

import android.graphics.Bitmap;

import java.util.concurrent.LinkedBlockingDeque;

//请求队列管理
public class RequestManager {
    private static RequestManager requestManager = new RequestManager();
    //请求队列
    private LinkedBlockingDeque<BitmapRequest> mQueue;
    //线程数组
    private BitmapDispatch[] bitmapDispatches;

    public RequestManager() {
        mQueue = new LinkedBlockingDeque<>();
        createAndOpenThread();
    }

    private void createAndOpenThread() {
        //获取应用最大线程数
        int count = Runtime.getRuntime().availableProcessors();
        bitmapDispatches = new BitmapDispatch[count];
        for (int i = 0; i<count; i++){
            BitmapDispatch bitmapDispatch = new BitmapDispatch(mQueue);
            bitmapDispatch.start();
            bitmapDispatches[i] = bitmapDispatch;
        }
    }

    public static RequestManager getInstance(){
        return requestManager;
    }

    public void addBitmapRequest(BitmapRequest bitmapRequest){
        if (bitmapRequest != null && !mQueue.contains(bitmapRequest)){
            mQueue.add(bitmapRequest);
        }
    }
    public void stop(){
        if (bitmapDispatches != null && bitmapDispatches.length>0){
            for (BitmapDispatch bitmapDispatch : bitmapDispatches){
                if (bitmapDispatch.isInterrupted()){
                    bitmapDispatch.interrupt();
                }
            }
        }
    }
}
